package com.gjszn.kh.mail;

import java.util.List;

import javax.inject.Inject;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.gjszn.kh.model.HtmlMailBean;

/**    
* @Title: MailSenderUtil.java  
* @Package com.gjszn.kh.mail    
* @author jys@nx-yt.com    
* @date 2016年1月18日 上午11:21:50  
* @version V1.0    
* @Description: TODO(用一句话描述该文件做什么)
********************************************/
public class MailSenderUtil {
	private static Logger log = LogManager.getLogger(MailSenderUtil.class);
	@Inject
	private MailSender mailSender;
	private String alias;
	// 默认邮件主题
	private String default_subject;
	
	public String getDefault_subject() {
		return default_subject;
	}

	public void setDefault_subject(String default_subject) {
		this.default_subject = default_subject;
	}

	public String getAlias() {
		return alias;
	}

	public void setAlias(String alias) {
		this.alias = alias;
	}
	
	public String getSubjectMark(){
		return "【" + getAlias() + "】";
	}
	
	private String getFrom(){
		String from = mailSender.getUsername();
		if(alias != null && !"".equals(alias)){
			from = alias + "<" + from + ">";
		}
		return from;
	}
	
	/**
	 * 给单个用户发送邮件
	 * 
	 * @param to
	 * @param subject
	 * @param content
	 * @param fromAlias
	 * @throws MessagingException void
	 */
	public void sendMail(String to, String subject, String content) throws MessagingException{
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");// 处理中文编码
		// 信息
		helper.setSubject(subject); // 主题
		helper.setFrom(getFrom()); // 发件人
		helper.setTo(to); // 收件人
		helper.setText(content, true); // 内容(HTML)
		// 发送
		mailSender.send(message);
		log.info(getFrom() + "给" + to + "的["+ subject +"]邮件已经成功发送");
	}
	
	/**
	 * 根据一组邮件内容，发送邮件
	 * 
	 * @param mailBeans void
	 */
	public void sendMail(HtmlMailBean mailBeans){
		try {
			this.sendMail(mailBeans.getTo(), 
					mailBeans.getSubject(), 
					mailBeans.getContent());
		} catch (MessagingException e) {
			log.warn(getFrom() + "给" + mailBeans.getTo() + "的["+ mailBeans.getSubject() +"]邮件发送失败：" + e.getMessage());
		}
	}
	
	/**
	 * 根据一组邮件内容，发送邮件
	 * 
	 * @param mailBeans void
	 */
	public void sendMail(List<HtmlMailBean> mailBeans){
		for(HtmlMailBean htmlMailBean : mailBeans){
			sendMail(htmlMailBean);
		}
	}
}

